  <template>
    <div class="hostel">
      <div class="search">
        用户名：
        <el-input
          style="width: 145px; padding-right:10px"
          placeholder="请输入用户名"
          prefix-icon="el-icon-search"
          v-model="searchData.username">
        </el-input>

        房屋信息：
        <el-input
          style="width: 145px; padding-right:10px"
          placeholder="请输入房屋信息"
          prefix-icon="el-icon-search"
          v-model="searchData.buildNameAndCode">
        </el-input>

        <el-button style=" float: right; margin-left:10px;" @click="reset">重置</el-button>
        <el-button style=" float: right;" type="primary" @click="onSubmit">查询</el-button>
      </div>

      <div class="do">
        <el-button style="margin-left:10px;" @click="dialogFormVisible = true">新增</el-button>
        <el-button v-if="user.position === 2" @click="batchDelete()">批量删除</el-button>
      </div>

      <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        :filters="[{ text: '女', value: 0 }, { text: '男', value: 1 }]"
        :filter-method="filterTag"
        filter-placement="bottom-end">
        <template slot-scope="scope">
            <el-tag
            :type="scope.row.sex === 0 ? 'primary' : 'success'"
            disable-transitions>{{getSexText(scope.row.sex)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="buildNameAndCode"
        label="房屋信息">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.buildNameAndCode" placement="top">
            <span>{{ String(scope.row.buildNameAndCode).length > 10? String(scope.row.buildNameAndCode).substring(0, 10) + '......' : scope.row.buildNameAndCode }}</span>
          </el-tooltip>
        </template>
      </el-table-column>  
      <el-table-column
        prop="position"
        label="角色"
        :filters="[{ text: '业主', value: 0 }, { text: '工作人员', value: 1 }, { text: '超级管理员', value: 2 }, { text: '维修人员', value: 3 }, { text: '普通用户', value: 4 }]"
        :filter-method="filterTag1"
        filter-placement="bottom-end">
        <template slot-scope="scope">
            <el-tag 
            :type="scope.row.sex === 2 ? 'primary' : 'success'"
            disable-transitions>{{getPositionText(scope.row.position)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.position !== 1 && scope.row.position !== 2"
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            v-if="user.position === 2"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>

      <div class="block" style="margin-top: 20px; text-align: right; margin-right: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>

      <OwnerFormPop class="houseFormPop" @updateFormData="updateFormData" :user="user" :hostelBuildArray="hostelBuildArray" :title.sync="title" :formData="updateTableData" v-show="dialogFormVisible" :visible.sync="dialogFormVisible"></OwnerFormPop>
    </div>
  </template>
           
  <script>
  import api from '@/api';
  import { cloneDeep } from 'lodash';
  import OwnerFormPop from './OwnerFormPop';
  import { mapState,mapMutations } from "vuex"

  export default {
    computed:{
      ...mapState("login",["user"])
    },
      components: {
        OwnerFormPop,
      },
      data() {
        return {
          buildNameAndCode:'',
          options:[],
          hostelOptionsMap: new Map(),
          hostelBuildArray:[],
          hostelBuildSaleArray:[],
          title: '新增用户',
          currentPage: 1,
          total:100,
          pageSize:10,
          dialogFormVisible: false,
          searchData:{
            pageNow: 1,
          },
          tableData: [{
            id:'',
            username:'',
            buildNameAndCode: '状元楼-302',
            buildId:'',
            position: 0,
            email:"",
            sex: 0,
            createTime:"",
          }],
          selectedRow:[],
          updateTableData:{
            id:'',
            username:'',
            buildNameAndCode: '',
            buildNameAndCodeArray: [],
            buildId:'',
            position: 0,
            email:"",
            sex: 0,
          }
        }
      },
      methods: {
        updateFormData(data){
          this.updateTableData = data;
        },
        getSexText(sex){
          switch(sex){
              case 1 : return '男';
              case 0 : return '女';
            default : return '';
            }
        },
        getPositionText(status){
            switch(status){
              case 0 : return '业主';
              case 1 : return '工作人员';
              case 2 : return '超级管理员';
              case 3 : return '维修人员';
              case 4 : return '普通用户';
              default : return '';
            }
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
          this.searchData.pageNow = val
          //获取房屋信息
          this.onSubmit();
        },
        handleSelectionChange(selection) {
            this.selectedRow = selection
        },
        handleEdit(index, row) {
          this.updateTableData = row;
          this.dialogFormVisible = true;
          this.title = '编辑人员'
          this.updateTableData.buildNameAndCodeArray = []
          if(this.updateTableData.buildNameAndCode){
            const buildNames = this.updateTableData.buildNameAndCode.split(",");

            const newHostelBuildArray = cloneDeep(this.hostelBuildArray)

            buildNames.forEach((name) => {
                //去除空格
                const trimeName = name.trim();
                const marchItem = this.hostelBuildSaleArray.find((item) => item.label === trimeName);

                if(marchItem){
                  this.updateTableData.buildNameAndCodeArray.push(marchItem.value)
                  newHostelBuildArray.push(marchItem)
                }
            })

            this.updateTableData.newHostelBuildArray = newHostelBuildArray
          }
        },
        handleDelete(index, row) {
          api.userDelete(row.id).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                this.tableData.splice(index,1)
                this.$message.success('删除成功');
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        filterTag(value, row) {
          return row.sex === value;
        },
        filterTag1(value, row) {
          return row.position === value;
        },
        //批量删除
        batchDelete(){
          var deleteIds = '';
          this.selectedRow.map(item =>{
            if(deleteIds === ''){
              deleteIds = item.id
            }else{
              deleteIds = deleteIds + "," + item.id
            }
          })
          if(deleteIds === ''){
            this.$message.error("请勾选删除项")
            return;
          }
          api.userDelete(deleteIds).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                this.$message.success('删除成功');
                this.selectedRow.map(item =>{
                  const index = this.tableData.findIndex((data) => data.id === item.id);
                  this.tableData.splice(index,1)
                })
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        onSubmit() {
          //获取用户信息
          api.getUserByPosition(true,true,this.searchData).then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                } else if (res.data.code === 200) {
                  let userInfoDTO = res.data.data.userList;

                    userInfoDTO.forEach(item => {
                      if(item.id){
                          const buildNameAndCode =this.hostelOptionsMap.get(item.id);
                          item.buildNameAndCode = buildNameAndCode;
                      }
                    });
                    if(this.searchData.buildNameAndCode){
                        userInfoDTO = userInfoDTO.filter(item => 
                          item.buildNameAndCode && item.buildNameAndCode.toLowerCase().includes(this.searchData.buildNameAndCode)
                        );
                    }                 
                  this.tableData = userInfoDTO;
                  this.total = res.data.data.total
                } else {
                  this.$message.error(res.data.message);
                }
          });

        },
        // 重置
        reset(){
          this.searchData.buildNameAndCode = '',
          this.searchData.username = '',
          this.onSubmit();
        },
        //查询楼宇信息
        getReceivers() {
          return new Promise((resolve, reject) => {
              api.buildListAll().then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.buildInfos;
                  this.options = tableData.map(item => ({
                    value: item.id,
                    label: item.buildingName + "-" + item.unit
                  }));
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
          });
        },
        //查询房屋信息
        getHostel() {
          return new Promise((resolve, reject) => {
              api.hostelList({}).then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.hostelInfos;

                  const optionsMap = this.options.reduce((map, option) => {
                        map[option.value] = option.label;
                        return map;
                  }, {});
                  tableData.forEach(item => {
                    if(item.buildId){
                        const buildName = optionsMap[item.buildId];
                        let map =  this.hostelOptionsMap.get(item.userId) ? this.hostelOptionsMap.get(item.userId) : '';
                        if(map){
                          this.hostelOptionsMap.set(item.userId,buildName+ '-' +item.hostelCode +','+map)
                        }else{
                          this.hostelOptionsMap.set(item.userId,buildName+ '-' +item.hostelCode)
                        }
                    }
                    if(item.buildId && !item.userId){
                      const buildName = optionsMap[item.buildId];

                      this.hostelBuildArray.push({
                        label: buildName+'-'+item.hostelCode,
                        value: item.id
                      })
                    }

                    if(item.buildId){
                      const buildName = optionsMap[item.buildId];

                      this.hostelBuildSaleArray.push({
                        label: buildName+'-'+item.hostelCode,
                        value: item.id
                      })
                    }
                  })
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
          });
        },      
      },
      created () {
        //获取房屋信息
        this.getReceivers().then(() => {
          this.getHostel().then(() => {
            this.onSubmit(); 
          });
        });
      },
  }
  </script>
  <style scoped>
  .hostel{
    background-color: #fff;
  }
  .hostel .search{
    padding: 10px;
  }
  .hostel .do{
    padding: 10px;
  }
  /* 自定义遮罩层样式 */
  .hostel .houseFormPop {
    background-color: rgba(0, 0, 0, 0.5); /* 遮罩层颜色 */
    z-index: 9999; /* 设置一个较高的 z-index 使遮罩层位于最上层 */
  }
  </style>